package com.itheima.home_work.work2;

import java.io.*;

public class Test {
    public static void main(String[] args) {
        // 测试
        String sourcePath = "D:\\codes\\java_test";
        String targetPaht = "D:\\codes\\images_test";

        copyImagesToDir(sourcePath, targetPaht);
    }

    public static void copyImagesToDir(String sourceDir, String targetDir) {
        File dirs = new File(sourceDir);
        File[] allFiles = dirs.listFiles();

        for (int i = 0; i < allFiles.length; i++) {
            File nowFile = allFiles[i];
            String path = nowFile.getPath();
            if (path.endsWith("jpg") || path.endsWith("jpeg") || path.endsWith("png")) {
                copyFileToDir(nowFile, targetDir);
            }
        }
    }

    // 复制文件到目标目录
    public static void copyFileToDir(File file, String targetDir) {


        try (
                // 1. 创建输入流对象
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(targetDir + "\\" + file.getName());
        ) {
            // 2. 读取流
            int len = -1;
            byte[] bytes = new byte[1024];
            while ((len = fis.read(bytes)) != -1) {
                // 3. 写入目标文件
                fos.write(bytes, 0, len);
            }
        } catch (Exception e) {
            System.out.println("异常：" + e.getMessage());
        }

    }
}
